package com.movie2.controller;

import com.movie2.config.MyConstants;
import com.movie2.model.entity.Registration;
import com.movie2.model.entity.User;
import com.movie2.model.entity.Worker;
import com.movie2.model.entity.WorkerEvaluate;
import com.movie2.model.vo.LoginVo;
import com.movie2.service.ActivityService;
import com.movie2.service.RegistrationService;
import com.movie2.service.WorkerEvaluateService;
import com.movie2.service.WorkerService;
import com.movie2.util.JwtTokenUtil;
import com.movie2.util.MD5Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.*;

@RestController
@RequestMapping("/api/worker")
@CrossOrigin
@Slf4j
public class WorkerController {
    @Autowired
    WorkerService workerService;

    @GetMapping("")
    public List<Worker> getWorker() {
        log.info("获得客服列表：WorkerController -> getWorker()");
        Worker temp = new Worker();
        temp.setEntry(1);
        temp.setDepartment("客服部");
        List<Worker> workerList = workerService.selectWorkersByCondition(temp);
        for (Worker worker : workerList) {
            worker.setAvatar(MyConstants.MY_URL+worker.getAvatar());
        }
        return workerList;
    }

    @Autowired
    WorkerEvaluateService workerEvaluateService;

    @GetMapping("/evaluate")
    public List<WorkerEvaluate> getWorkerEvaluate(@RequestParam("uid") Integer uid,
                                                  @RequestParam("wid") Integer wid) {
        log.info("获得我的评论列表：WorkerController -> getWorkerEvaluate()");
        WorkerEvaluate temp = new WorkerEvaluate();
        temp.setUid(uid);
        temp.setWid(wid);
        List<WorkerEvaluate> weList = workerEvaluateService.selectWorkerEvaluatesByCondition(temp);
        return weList;
    }

    @PostMapping("/evaluate/add")
    public Map<String, Object> addEvaluate(@RequestBody WorkerEvaluate workerEvaluate) {
        Map<String, Object> map = new HashMap<>();
        int count = workerEvaluateService.insert(workerEvaluate);
        if (count == 1) {
            map.put("success", "ok");
        } else {
            map.put("success", "fail");
        }
        return map;
    }


    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody LoginVo vo) {
        log.info("UserController ----> login(LoginVo vo)");
        Map<String, Object> map = new HashMap<>();
        Worker worker = new Worker();
        worker.setUsername(vo.getUsername());
        List<Worker> workers = workerService.selectWorkersByCondition(worker);
        if (workers == null || workers.size() == 0) {
            map.put("msg", "用户名或密码错误");
            map.put("success", "fail");
        } else {
            Worker result = workers.get(0);
            if (vo.getPassword().equalsIgnoreCase(result.getPassword())) {
                // 登录成功
                map.put("msg", "登录成功");
                map.put("success", "success");
                List<String> list = new ArrayList<>();
                list.add("worker");
                String token = JwtTokenUtil.createToken(result.getUsername(), list, JwtTokenUtil.EXPIRATION_TIME);
                map.put("token", token);
                map.put("worker", result);
            } else {
                // 密码加密后与数据库中存储的不一致
                map.put("msg", "用户名或密码错误");
                map.put("success", "fail");
            }
        }
        return map;
    }

    @Autowired
    ActivityService activityService;
    @Autowired
    RegistrationService registrationService;

    @GetMapping("/deleteActivity")
    public Map<String, Object> deleteActivity(@RequestParam("aid") Integer aid) {
        Map<String, Object> map = new HashMap<>();
        int count;
        count  = activityService.deleteByPrimaryKey(aid);
        Registration registration=new Registration();
        registration.setAid(aid);
        count= registrationService.deleteByCondition(registration);

        if (count == 1) {
            map.put("success", "ok");
        } else {
            map.put("success", "fail");
        }
        return map;
    }

    @GetMapping("/workerEvaluate")
    public List<WorkerEvaluate> workerEvaluate(@RequestParam("wid")Integer wid){
        WorkerEvaluate workerEvaluate=new WorkerEvaluate();
        workerEvaluate.setWid(wid);
        List<WorkerEvaluate> workerEvaluateList=workerEvaluateService.selectWorkerEvaluatesByCondition(workerEvaluate);


        return workerEvaluateList;
    }

    @GetMapping("/info")
    public Worker info(@RequestParam("wid")Integer wid){
        Worker worker=workerService.selectByPrimaryKey(wid);
        worker.setAvatar(MyConstants.MY_URL+worker.getAvatar());

        return worker;
    }

    @Value("${xhn.avatar.upload}")
    String avatarUploadPath;

    // 修改个人设置
    // 单文件上传
    @PostMapping("/avatar/upload")
    public Map<String, String> avatarUpload(@RequestBody MultipartFile file) throws IOException {
        log.info("头像上传：WorkerController类，upload()");
        Map<String, String> map = new HashMap<>();

        File path = new File(avatarUploadPath);
        if (!path.exists()) {
            path.mkdirs();//文件夹不存在，创建文件夹
        }
        String originalFilename = file.getOriginalFilename();//获得原始的文件名“7.jpg”
        int index = originalFilename.lastIndexOf(".");
        String newName = originalFilename.substring(0, index) + "_" + UUID.randomUUID().toString() + originalFilename.substring(index);
        // 保存文件
        try {
            file.transferTo(new File(avatarUploadPath + newName));//不出现异常，就是文件上传成功
            // 对数据库进行操作（把图片的路径保存到数据库中），varchar/char （建议使用）
            // blob二进制文件类型，把图片的二进制文件直接保存到数据库中，（很少用）
            map.put("message", "文件保存成功");
            map.put("db", "数据库保存成功");
            map.put("name", "/images/avatar/" + newName);
            // return "不出现异常，就是文件上传成功";
        } catch (IOException ioException) {
            map.put("message", "文件保存失败");
            ioException.printStackTrace();//文件上传失败
            // return "出现异常，文件上传失败";
            throw ioException;
        }
        return map;
    }

    @PostMapping("/update")
    public Map<String, Object> updateSet(@RequestBody Worker worker) {
        log.info("修改个人设置：UserController -> updateSet(@RequestBody User user)");
        Map<String, Object> map = new HashMap<>();
        Worker result = workerService.selectByPrimaryKey(worker.getId());
        int isA = worker.getAvatar().indexOf(MyConstants.MY_URL);
        if (isA != -1) {
            worker.setAvatar(worker.getAvatar().replace(MyConstants.MY_URL, ""));
        }

        int count = workerService.updateByPrimaryKey(worker);
        if (count == 1) {
            map.put("success", "ok");
        }
        return map;
    }
}
